package sailhero

import (
	"fmt"
	"github.com/wsw188440873/ctrl-cali/types"
	"sort"
	"strconv"
)

// linearityError 计算线性误差
//{
//	"avg": {
//	"100": [81, 87, 47, 62, 89, 28, 47, 47, 87],
//	"200": [59, 81, 18, 74, 11, 45, 88, 90, 15],
//	"300": [25, 40, 56, 37, 6, 95, 41, 8, 87],
//	"400": [0, 94, 11, 66, 28, 58, 31, 29, 56]
//	}
//}
func linearityError(modelId string, params map[string]interface{}) ([]float64, bool) {
	if _, ok := params["collect_data"]; !ok {
		return []float64{}, false
	}
	if _, ok := types.Range[modelId]; !ok {
		return []float64{}, false
	}
	avgMap := params["collect_data"].(map[string][]float64)
	avgMapLen := len(avgMap)
	lValue := make([]float64, 0, avgMapLen)
	// 计算每次采集的平均值.
	for key, values := range avgMap {
		fmt.Println("avgMap key", key)
		valueLen := len(values)
		valueSum := float64(0)
		for _, v := range values {
			valueSum += v
		}
		// 计算平均数.
		average := valueSum / float64(valueLen)
		// 标准气体浓度值 todo 这里有问题
		number, _ := strconv.Atoi(key)
		// 待测分析仪器满量程值
		r := types.Range[modelId]
		fkey := float64(number) / r
		sKey := strconv.FormatFloat(fkey, 'f', 1, 64)
		fmt.Println("types.LinearityErrorRang[key]", types.LinearityErrorRang[sKey])

		si := r * types.LinearityErrorRang[sKey]
		le := (average - si) / r
		lValue = append(lValue, le*100)
	}
	sort.Slice(lValue, func(i, j int) bool {
		return lValue[i] > lValue[j]
	})
	return append([]float64{}, lValue...), true
}
